﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;
using TomanuExtensions;

namespace RaytracerLib.MathLib.PolynomialFunction
{
    public class TreeReplacer
    {
        public readonly Element Old;
        public readonly Element New;

        public TreeReplacer(Element a_old, Element a_new)
        {
            Old = a_old;
            New = a_new;
        }

        public static bool CanReplace(IEnumerable<TreeReplacer> a_replacers, Element a_old, out Element a_new)
        {
            if (a_replacers == null)
            {
                a_new = null;
                return false;
            }

            TreeReplacer tr = a_replacers.FirstOrDefault(r => Object.ReferenceEquals(r.Old, a_old));

            if (tr == null)
            {
                a_new = null;
                return false;
            }

            a_new = tr.New;
            return true;
        }

        public static Element ReplaceOrClone(IEnumerable<TreeReplacer> a_replacers, Element a_old, ref bool a_cloned)
        {
            if (a_replacers == null)
                return a_old.CloneTree();

            TreeReplacer tr = a_replacers.FirstOrDefault(r => Object.ReferenceEquals(r.Old, a_old));

            if (tr == null)
                return a_old.CloneTree(a_replacers);

            a_cloned = false;

            return tr.New;
        }
    }
}
